﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Boiling.Common;

namespace Boiling.BizFacade
{
    using System;
    using System.Data;
    
    using Boiling.Common;
    using Boiling.DataAccess;

    using System.Text.RegularExpressions;

    public class c_UserInfo
    {
        public String userID;
        public String userNo;
        public String userName;
        public String userLogdate;
        public String userSchool;
        public String userAge;
        public String userStudynum;
        public String userSex;
    }

    public class c_UserAddInfo
    {
        public String userID;
        public String userSports;
        public String userMovie;
        public String userMusic;
        public String userBooks;
    }

    
    /// <summary>
    ///     facade层
    ///     <remarks>
    ///         The BoilingFacade is used to provide a simplified interface into the 
    ///         member sub systems.
    ///     </remarks>
    ///     <remarks>
    ///         This class is marked as MarshalByRefObject to support remoted scenarios. 
    ///     </remarks>
    /// </summary>
    public class UserSystem : MarshalByRefObject
    { 
        /// <summary>
        /// 通过用户名和密码登陆
        /// </summary>
        /// <param name="emailaddress">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>登陆状态</returns>
        public int GetUserByEmail(String emailaddress, String password)
        {
            //
            // Check preconditions
            //登录用户名是否合法，合法的用户名因为邮箱，若不合法返回-1
            //密码不正确，返回0
            //登录成功，返回1
            //不存在此用户，返回2

            //判断邮箱以及密码是否为空，均不为空才能继续
            try
            {
                if (emailaddress.Length == 0)
                    return -1;
                if (password.Length == 0)
                    return 0;
            }
            catch (System.Exception e)
            {
                return -1;
            }
            

            //以正则表达式判断用户名是否合法，即是否为邮箱
            if( !isUserIDLegal(emailaddress))
                return -1;

            //判断用户是否存在
            if (!(new DataAccess.b_User()).checkuserbyID(emailaddress))
                return 2;

            //用户名密码是否匹配

            //
            // Get the customer dataSet
            //
            b_Userdata dataSet;
            using (DataAccess.b_User customersDataAccess = new DataAccess.b_User())
            {
                dataSet = customersDataAccess.getuserbyID(emailaddress);
            }
            //    
            // Verify the customer's password
            //
            DataRowCollection rows = dataSet.Tables[b_Userdata.b_User_Table].Rows;

            if ((rows.Count == 1) && rows[0][b_Userdata.User_Pwd_Field].Equals(password))
                return 1;
            else
                return 0;
        }

 

        /// <summary>
        /// 判断用户名是否合法，即用户名是否是邮箱地址
        /// </summary>
        /// <param name="emailaddress"></param>
        /// <returns></returns>
        public bool isUserIDLegal(String emailaddress)
        {
            string pattern = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            bool match = Regex.IsMatch(emailaddress, pattern);
            return match;
        }


        /// <summary>   
        ///     Creates a new user.
        ///     <remarks>userData is passed back as an out parameter for remoting.</remarks>
        ///     <param name="emailAddress">User's email address.</param>
        ///     <param name="password">User's account password.</param>
        ///     <param name="name">User's name.</param>
        ///     <param name="address">User's address.</param>
        ///     <param name="country">User's country.</param>
        ///     <param name="phoneNumber">User's phone number.</param>
        ///     <param name="fax">User's fax number.</param>
        ///     <param name="userData">Returns User's data.</param>
        ///     <param name="userInfoData">Returns User's Infodata.</param>
        ///     <retvalue>true if Create is successful: otherwise, false.</retvalue>
        ///     
        /// 
        ///     验证码不正确返回2
        ///     两次密码不相同返回3
        ///     创建用户成功返回1
        ///     创建失败返回0
        ///     若注册邮箱已经存在，返回4
        public int CreatUser(String username, String emailaddress, String password, String password_check, String  studynum, 
                             String school, String age, String sex, out b_Userdata userData, out b_UserInfodata userInfoData)
        {
            userData = new b_Userdata();
            userInfoData = new b_UserInfodata();
            
            if ((new DataAccess.b_User()).checkuserbyID(emailaddress))
                return 4;

            //两次输入密码不相同
            if(!password.Equals(password_check))
                return 3;
            
            
            //
            // Create a new row
            //
            DataTable table = userData.Tables[b_Userdata.b_User_Table];
            DataRow row = table.NewRow();
            //
            // Fill input data into new row
            //
            row[b_Userdata.User_ID_Field] = emailaddress;
            row[b_Userdata.User_Pwd_Field] = password;
            //
            // Add it to the table
            //
            table.Rows.Add(row);


            table = userInfoData.Tables[b_UserInfodata.b_UserInfo_Table];
            row = table.NewRow();
            row[b_UserInfodata.User_ID_Field] = emailaddress;
            row[b_UserInfodata.User_Name_Field] = username;
            row[b_UserInfodata.User_Logdate_Field] = System.DateTime.Now.ToString("yyyy年MM月dd日hh时mm分ss秒");
            row[b_UserInfodata.User_School_Field] = school;

            if (age.Equals(""))
                age = "0";
            row[b_UserInfodata.User_Age_Field] = Int32.Parse(age);
            row[b_UserInfodata.User_Studynum_Field] = Int32.Parse(studynum);

            if (sex.Equals("男"))
                row[b_UserInfodata.User_Sex_Field] = true;
            else
                row[b_UserInfodata.User_Sex_Field] = false;

            //add rows
            table.Rows.Add(row);


            if ((new b_User()).insertuserbydata(userData) && (new b_UserInfo()).insertuserinfo(userInfoData))
                return 1;
            else 
                return 0;
        }


        /// <summary>
        /// 注册时添加修改UserConInfodata
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="location"></param>
        /// <param name="mobile"></param>
        /// <param name="qqnumber"></param>
        /// <param name="msn"></param>
        /// <param name="userConInfodata"></param>
        /// <returns></returns>
        public bool addConInfodata(String userId, String location, String mobile, String qqnumber, String msn, out b_UserConInfodata userConInfodata)
        {
            userConInfodata = new b_UserConInfodata();
            
            try
            {
                DataTable table = userConInfodata.Tables[b_UserConInfodata.b_UserConInfo_Table];
                DataRow row = table.NewRow();

                row[b_UserConInfodata.User_ID_Field] = userId;
                row[b_UserConInfodata.User_Location_Field] = location;
                row[b_UserConInfodata.User_Mobile_Field] = mobile;
                row[b_UserConInfodata.User_MSN_Field] = msn;
                row[b_UserConInfodata.User_QQ_Field] = qqnumber;

                table.Rows.Add(row);

                return (new b_UserConInfo()).insertuserconinfo(userConInfodata);
            }
            catch (System.Exception e)
            {      
                return false;
            }
        }


        /// <summary>
        /// 注册时添加修改AddInfodata
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="sports"></param>
        /// <param name="movie"></param>
        /// <param name="music"></param>
        /// <param name="books"></param>
        /// <param name="userAddInfodata"></param>
        /// <returns></returns>
        public bool addAddInfodata(String userId, String sports, String movie, String music, String books, out b_UserAddInfodata userAddInfodata)
        {
            userAddInfodata = new b_UserAddInfodata();

            try
            {
                DataTable table = userAddInfodata.Tables[b_UserAddInfodata.b_UserAddInfo_Table];
                DataRow row = table.NewRow();

                row[b_UserAddInfodata.User_ID_Field] = userId;
                row[b_UserAddInfodata.User_Sports_Field] = sports;
                row[b_UserAddInfodata.User_Music_Field] = music;
                row[b_UserAddInfodata.User_Movie_Field] = movie;
                row[b_UserAddInfodata.User_Books_Field] = books;

                table.Rows.Add(row);

                return (new b_UserAddInfo()).insertuseraddinfo(userAddInfodata);
            }
            catch (System.Exception e)
            {
                return false;
            }
        }


        /// <summary>   
        ///      修改注册信息
        ///     <remarks>Userdata is passed back as an out parameter for remoting.</remarks>
        ///     <param name="emailAddress">User's email address.</param>
        ///     <param name="password">User's account password.</param>
        ///     <param name="name">User's name.</param>
        ///     <param name="address">User's address.</param>
        ///     <param name="country">User's country.</param>
        ///     <param name="phoneNumber">User's phone number.</param>
        ///     <param name="fax">User's fax number.</param>
        ///     <param name="Userdata">Returns User's data.</param>
        ///     <retvalue>true if Create is successful: otherwise, false.</retvalue>
        ///     成功返回true，失败返回false
        /// 

        /// </summary>
        public bool editUserdata(String username, String emailaddress, String password, String password_check, String studynum,
                             String school, String age, String sex, out b_Userdata userData, out b_UserInfodata userInfoData)
        {
            userData = new b_Userdata();
            userInfoData = new b_UserInfodata();

            try
            {
                //两次输入密码不相同
                if (!password.Equals(password_check))
                    return false;


                //
                // Create a new row
                //
                DataTable table = userData.Tables[b_Userdata.b_User_Table];
                DataRow row = table.NewRow();  
                //
                // Fill input data into new row
                //
                row[b_Userdata.User_ID_Field] = emailaddress;
                row[b_Userdata.User_Pwd_Field] = password;
                //
                // Add it to the table
                //
                table.Rows.Add(row);


                table = userInfoData.Tables[b_UserInfodata.b_UserInfo_Table];
                row = table.NewRow();
                row[b_UserInfodata.User_ID_Field] = emailaddress;
                row[b_UserInfodata.User_Name_Field] = username;
                row[b_UserInfodata.User_Logdate_Field] = System.DateTime.Now.ToString("yyyy年MM月dd日hh时mm分ss秒");
                row[b_UserInfodata.User_School_Field] = school;
                row[b_UserInfodata.User_Age_Field] = Int32.Parse(age);
                row[b_UserInfodata.User_Studynum_Field] = Int32.Parse(studynum);

                if (sex.Equals("男"))
                    row[b_UserInfodata.User_Sex_Field] = true;
                else
                    row[b_UserInfodata.User_Sex_Field] = false;

                //add rows
                table.Rows.Add(row);


                if ((new b_User()).modifyuserbydata(userData) && (new b_UserInfo()).modifyuserinfo(userInfoData))
                    return true;
                else
                    return false;
            }
            catch (System.Exception ex)
            {
                return false;
            }
        }


        /// <summary>
        /// 修改UserConInfodata
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="location"></param>
        /// <param name="mobile"></param>
        /// <param name="qqnumber"></param>
        /// <param name="msn"></param>
        /// <param name="userConInfodata"></param>
        /// <returns></returns>
        public bool editConInfodata(String userId, String location, String mobile, String qqnumber, String msn, out b_UserConInfodata userConInfodata)
        {
            userConInfodata = new b_UserConInfodata();

            try
            {
                DataTable table = userConInfodata.Tables[b_UserConInfodata.b_UserConInfo_Table];
                DataRow row = table.NewRow();

                row[b_UserConInfodata.User_ID_Field] = userId;
                row[b_UserConInfodata.User_Location_Field] = location;
                row[b_UserConInfodata.User_Mobile_Field] = mobile;
                row[b_UserConInfodata.User_MSN_Field] = msn;
                row[b_UserConInfodata.User_QQ_Field] = qqnumber;

                table.Rows.Add(row);

                return (new b_UserConInfo()).modifyuserconinfo(userConInfodata);
            }
            catch (System.Exception e)
            {
                return false;
            }
        }


        /// <summary>
        /// 修改AddInfodata
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="sports"></param>
        /// <param name="movie"></param>
        /// <param name="music"></param>
        /// <param name="books"></param>
        /// <param name="userAddInfodata"></param>
        /// <returns></returns>
        public bool editAddInfodata(String userId, String sports, String movie, String music, String books, out b_UserAddInfodata userAddInfodata)
        {
            userAddInfodata = new b_UserAddInfodata();

            try
            {
                DataTable table = userAddInfodata.Tables[b_UserAddInfodata.b_UserAddInfo_Table];
                DataRow row = table.NewRow();

                row[b_UserAddInfodata.User_ID_Field] = userId;
                row[b_UserAddInfodata.User_Sports_Field] = sports;
                row[b_UserAddInfodata.User_Music_Field] = music;
                row[b_UserAddInfodata.User_Movie_Field] = movie;
                row[b_UserAddInfodata.User_Books_Field] = books;

                table.Rows.Add(row);

                return (new b_UserAddInfo()).modifyuseraddinfo(userAddInfodata);
            }
            catch (System.Exception e)
            {
                return false;
            }
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="emailaddress"></param>
        /// <param name="oldpassword"></param>
        /// <param name="newpassword1"></param>
        /// <param name="newpassword2"></param>
        /// <returns></returns>
        public int ResetPassword(String emailaddress,string oldpassword,string newpassword1,string newpassword2)
        {
            //emailaddress是待修改的用户邮箱
            //newpassword是修改后的密码
            //oldpassword是修改前的密码
            //返回1表示用户不存在
            //返回2表示用户存在但原密码输入错误
            //返回3表示用户存在，原密码正确，但两次新密码不一致
            //返回4表示用户密码修改成功
            b_User cmd = new b_User();
            if (!cmd.checkuserbyID(emailaddress))
                return 1;
          
            else
            {
                b_Userdata olddata= cmd.getuserbyID(emailaddress);
                if (!olddata.Tables["b_User"].Rows[0][1].Equals(oldpassword))
                    return 2;
                else if (!newpassword1.Equals(newpassword2))
                    return 3;
                else
                {
                    b_Userdata newdata = new b_Userdata();
                    DataRow newrow = newdata.Tables["b_User"].NewRow();
                    newrow[0] = emailaddress;
                    newrow[1] = newpassword1;
                    newdata.Tables["b_User"].Rows.Add(newrow);
                    cmd.modifyuserbydata(newdata);
                    return 4;
                }
            }
            
        }

        /// <summary>
        /// 强制删除非法用户
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public bool EnforceUserDelet(String username)
        {            
            return (new b_User()).deleteuserbyID(username);          
        }

        
        /// <summary>
        /// 通过用户邮箱返回UserInfo的封装类
        /// </summary>
        /// <param name="hostID">用户邮箱</param>
        /// <returns>UserInfo封装类</returns>
        public c_UserInfo GetUserInfodatabyID(String hostID)
        {
            c_UserInfo userinfo = new c_UserInfo();
            b_UserInfodata userInfoData = new b_UserInfodata();
            userInfoData = (new b_UserInfo()).getuserinfobyID(hostID);
            if (userInfoData.Tables[b_UserInfodata.b_UserInfo_Table].Rows.Count == 0)
                return null;

            userinfo.userID = userInfoData.Tables[b_UserInfodata.b_UserInfo_Table].Rows[0][b_UserInfodata.User_ID_Field].ToString();
            userinfo.userNo = (new UserSystem()).GetUserNoByUserID(userinfo.userID).ToString();
            userinfo.userName = userInfoData.Tables[b_UserInfodata.b_UserInfo_Table].Rows[0][b_UserInfodata.User_Name_Field].ToString();
            userinfo.userLogdate = userInfoData.Tables[b_UserInfodata.b_UserInfo_Table].Rows[0][b_UserInfodata.User_Logdate_Field].ToString();
            userinfo.userSchool = userInfoData.Tables[b_UserInfodata.b_UserInfo_Table].Rows[0][b_UserInfodata.User_School_Field].ToString();
            userinfo.userAge = userInfoData.Tables[b_UserInfodata.b_UserInfo_Table].Rows[0][b_UserInfodata.User_Age_Field].ToString();
            userinfo.userStudynum = userInfoData.Tables[b_UserInfodata.b_UserInfo_Table].Rows[0][b_UserInfodata.User_Studynum_Field].ToString();
            if ((bool)(userInfoData.Tables[b_UserInfodata.b_UserInfo_Table].Rows[0][b_UserInfodata.User_Sex_Field]))
                userinfo.userSex = "男";
            else
                userinfo.userSex = "女";

            return userinfo;
        }


        /// <summary>
        /// 根据用户id返回用户的UserAddInfoData封装类
        /// </summary>
        /// <param name="hostID">用户id</param>
        /// <returns>UserAddInfoData封装类</returns>
        public c_UserAddInfo GetUserAddInfodatabyID(String hostID)
        {
            c_UserAddInfo useraddinfo = new c_UserAddInfo();
            b_UserAddInfodata userAddInfoData = new b_UserAddInfodata();
            userAddInfoData = (new b_UserAddInfo()).getuseraddinfobyID(hostID);
            if (userAddInfoData.Tables[b_UserAddInfodata.b_UserAddInfo_Table].Rows.Count == 0)
                return null;

            useraddinfo.userID = userAddInfoData.Tables[b_UserAddInfodata.b_UserAddInfo_Table].Rows[0][b_UserAddInfodata.User_ID_Field].ToString();
            useraddinfo.userMovie = userAddInfoData.Tables[b_UserAddInfodata.b_UserAddInfo_Table].Rows[0][b_UserAddInfodata.User_Movie_Field].ToString();
            useraddinfo.userMusic = userAddInfoData.Tables[b_UserAddInfodata.b_UserAddInfo_Table].Rows[0][b_UserAddInfodata.User_Music_Field].ToString();
            useraddinfo.userBooks = userAddInfoData.Tables[b_UserAddInfodata.b_UserAddInfo_Table].Rows[0][b_UserAddInfodata.User_Books_Field].ToString();
            useraddinfo.userSports = userAddInfoData.Tables[b_UserAddInfodata.b_UserAddInfo_Table].Rows[0][b_UserAddInfodata.User_Sports_Field].ToString();

            return useraddinfo;
        }


        






        public void IncVisitorcount()
        {
            //
            //increase the number of the visitors in the database.
            //
            new b_User().IncVisitorcount();
        }

        public String GetVisitorcount()
        {
            //
            //return the number of the visitors
            //
            return (new b_User().GetVisitorcount()).ToString();
        }


        /// <summary>
        /// 给定用户邮箱返回用户No
        /// </summary>
        /// <param name="userID">用户邮箱</param>
        /// <returns>用户No</returns>
        public String GetUserNoByUserID(String userID)
        {
            return (new b_User()).getNObyID(userID).ToString();
        }


        /// <summary>
        /// 通过用户No返回用户邮箱
        /// </summary>
        /// <param name="userNo">用户No</param>
        /// <returns>用户邮箱</returns>
        public String GetUserIDByUserNo(String userNo)
        {
            return (new b_User()).getIDbyNO(Int32.Parse(userNo));
        }


        /// <summary>
        /// 返回最新注册的五个用户的昵称和注册时间
        /// 0-4为用户昵称，5-9为响应的注册时间
        /// </summary>
        /// <returns></returns>
        public String[] GetLatestFiveUsername()
        {
            String[] res = new String[10];
            b_UserInfodata userinfodata = new b_UserInfodata();
            userinfodata = (new b_UserInfo()).returnalldata();
            int n = userinfodata.Tables[b_UserInfodata.b_UserInfo_Table].Rows.Count;
            for (int i = 0; i < 5; i++ )
            {
                res[i] = userinfodata.Tables[b_UserInfodata.b_UserInfo_Table].Rows[n - i - 1][b_UserInfodata.User_Name_Field].ToString();
            }

            for (int i = 5; i < 10;i++ )
            {
                res[i] = userinfodata.Tables[b_UserInfodata.b_UserInfo_Table].Rows[n - i - 1 + 5][b_UserInfodata.User_Logdate_Field].ToString();
            }
            return res;
        }



    }    //class UserSystem
}  // namespace Boiling.BoilingFacade
